import React, { useState, useEffect } from 'react';
import { Table, Button } from 'antd';
import { randomKey } from 'src/utils/utils';
/**
 *  表格编辑器组件 TableEditor
 *  @props
 *  @param dataSource {Array} 同antd的dataSource 表格数据
 *  @param columns {Array} 同antd的columns 表格列的定义
 *  @param onChange {Function} 组件的值data变化时的回调函数
 *  @param initItem {Object} 默认添加一行时的初始化数据
 *  @param isInitOne {Boolean} 当没有值时，是否默认添加一行，默认false
 *  @param noNeedAdd {Boolean} 是否展示添加按钮，默认false
 *  @param disabled {Boolean} 是否禁止所有动作，默认false
 *  @param getButtonGroup {Function}
 *  @param operaterWidth {Number} 操作列宽度
 *   用作操作列的按钮，
 *    返回空时，不展示操作列，
 *    默认输出删除按钮，
 *    当然也可以将你自定义的按钮，输出在此数组中，用于灵活定义操作列的button
 *   ({ moveUpButton, moveDownButton, removeButton })=>{ return [moveUpButton, moveDownButton, removeButton]}
 */
export default function TableEditor({
  dataSource,
  columns,
  onChange,
  initItem = {},
  isInitOne = false,
  noNeedAdd = false,
  disabled = false,
  operaterWidth = undefined,
  getButtonGroup = ({ removeButton }) => {
    return [removeButton];
  },
}) {
  const [data, setData] = useState(dataSource || []);
  const moveUpButton = (text, record, index) => {
    return (
      <Button type='link' onClick={() => move(record, index, 'up')} disabled={index === 0}>
        上移
      </Button>
    );
  };
  const moveDownButton = (text, record, index) => {
    return (
      <Button type='link' onClick={() => move(record, index, 'down')} disabled={data.length - 1 === index}>
        下移
      </Button>
    );
  };
  const removeButton = (text, record, index) => {
    return (
      <Button type='link' onClick={() => remove(index)}>
        删除
      </Button>
    );
  };

  useEffect(() => {
    if (dataSource.length > 0) {
      // console.log(dataSource)
      if (dataSource[0]) setData(initData(dataSource));
    } else {
      if (isInitOne) {
        addItem();
      }
    }
  }, [dataSource]);

  function initData(data) {
    const newData = data.map((item) => {
      item.id = item.id ? item.id : randomKey();
      return item;
    });
    return newData;
  }

  //添加一条
  function addItem() {
    const item = {
      id: randomKey(),
      ...initItem,
    };
    data.push(item);
    setData(Object.assign([], data));
    onChange && onChange(data);
  }

  // 删除
  function remove(index) {
    data.splice(index, 1);
    setData(Object.assign([], data));
    onChange && onChange(data);
  }

  // 移动
  function move(item, index, step) {
    // 下移
    if (step === 'down') {
      data.splice(index, 1); //移除当前项
      data.splice(index + 1, 0, item); // 在index+1处插入当前item
      // 上移
    } else if (step === 'up') {
      data.splice(index, 1); //移除当前项
      data.splice(index - 1, 0, item); // 在index-1处插入当前item
    }
    setData(Object.assign([], data));
    onChange && onChange(data);
  }

  // 操作项
  const buttonGroup = getButtonGroup({ moveUpButton, moveDownButton, removeButton });
  const buttonOperater =
    buttonGroup.length > 0 && !disabled
      ? {
          title: '操作',
          width: operaterWidth,
          render: (text, record, index) => {
            return (
              <>
                {buttonGroup.map((it) => (
                  <span key={it}>{it(text, record, index)}</span>
                ))}
              </>
            );
          },
        }
      : false;

  return (
    <div>
      {!noNeedAdd && (
        <Button type='primary' className='mb-10' onClick={() => addItem()}>
          添加
        </Button>
      )}

      <Table
        columns={[...columns, buttonOperater].filter(Boolean)}
        dataSource={data}
        rowKey={(record, index) => index}
        className='fixed'
        pagination={false}
      />
    </div>
  );
}
